import cv2
import numpy as np

def cv_show(name,img):
    cv2.imshow(name,img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def detectAndDescribe(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    descriptor = cv2.xfeatures2d.SIFT_create()
    (kps, features) = descriptor.detectAndCompute(image, None)
    kps = np.float32([kp.pt for kp in kps])
    return (kps, features)

imageA = cv2.imread("img2.jpg")
imageB = cv2.imread("img1.jpg")

print(imageA.shape)
print(imageB.shape)
(kpsA, featuresA) = detectAndDescribe(imageA)
(kpsB, featuresB) = detectAndDescribe(imageB)

matcher = cv2.BFMatcher()
rawMatches = matcher.knnMatch(featuresA, featuresB, 2)
matches = []
good = []
for m in rawMatches:
    if len(m) == 2 and m[0].distance < m[1].distance * 0.85:
        matches.append((m[0].trainIdx, m[0].queryIdx))
        good.append([m[0]])

if len(matches) > 4:

    ptsA = np.float32([kpsA[i] for (_, i) in matches])
    ptsB = np.float32([kpsB[i] for (i, _) in matches])

    (H, status) = cv2.findHomography(ptsA, ptsB, cv2.RANSAC, 4.0)
    print(H)
# result = cv2.warpPerspective(imageA, H, (imageA.shape[1]+imageB.shape[1], imageA.shape[0]))
result = cv2.warpPerspective(imageA, H, (imageA.shape[1], imageA.shape[0] +imageB.shape[0]))
cv_show('result1', result)
print(result.shape)
result[0:imageB.shape[0], 0:imageB.shape[1]] = imageB
cv_show('result2', result)
print(result.shape)

(hA, wA) = imageA.shape[:2]
(hB, wB) = imageB.shape[:2]
vis = np.zeros((max(hA, hB), wA + wB, 3), dtype="uint8")
vis[0:hA, 0:wA] = imageA
vis[0:hB, wA:] = imageB

for ((trainIdx, queryIdx), s) in zip(matches, status):
    if s == 1:
        ptA = (int(kpsA[queryIdx][0]), int(kpsA[queryIdx][1]))
        ptB = (int(kpsB[trainIdx][0]) + wA, int(kpsB[trainIdx][1]))
        cv2.line(vis, ptA, ptB, (0, 255, 0), 1)
cv_show('vis',vis)
